﻿var g_vSymptomStrs=[];
var g_vSymptomXmlDoc='';
function getSymptomFlash()
{
    if (typeof(g_vSymptomFlash)=="undefined") 
    {
        g_vSymptomFlash="Symptomchart";
    }
    return g_vSymptomFlash;
}
function GetSymptomDegreeColor(iDegreeValue)
{
    return ["#008844","#F1D827","#FF8A15","#C60000"][iDegreeValue]
}
function GetSymptomDegreeText(iDegreeValue)
{
    return ["无","轻度","中度","重度"][iDegreeValue]
}
function OnSymptomFlashReady(id)
{
   //setTimeout("loadSymptomFlashData('"+id+"')",500);
   loadSymptomFlashData(id);
}
function CreateFlashDegreeText(id)
{
  var   table = document.createElement('<TABLE>');
  table.id = "_ID_SYMPTOM_DEGREETEXT_"+id;
  table.style.width="700px"
  table.style.textAlign="center"; 
  table.style.border="1px";
  table.style.backgroundColor="#FFFFFF"
  table.style.borderColor="#dddddd";
  var   tr = table.insertRow(-1);
  var td = tr.insertCell(-1);
  td.style.width="40px";
  for(var i=0;i< 4; ++i)
  {
     var td = tr.insertCell(-1);
     td.style.backgroundColor=GetSymptomDegreeColor(i);
     td.style.width="6px";
     td.style.borderColor="#fdfdfd"
     td.innerHTML="&nbsp;";
     td = tr.insertCell(-1);
     td.innerHTML=GetSymptomDegreeText(i);
     td.style.width="20px";
     td = tr.insertCell(-1);
     td.style.width="20px";
  }
  
  var flashDiv= _$(getSymptomFlash()+"1");
  flashDiv.parentNode.insertBefore(table,flashDiv);
}
function CreateMainOtherSymptom(id,iMain, iOther)
{
  if($("_ID_SYMPTOM_"+id) != null) return ;
  var flashDiv= _$(getSymptomFlash()+id);
  flashDiv.parentNode.className="symchartcontent"
  flashDiv.className="symchartright";
  
  tb=document.createElement('<TABLE>');
  tb.id = "_ID_SYMPTOM_"+id ;
  tb.cellpadding="0px";
  tb.cellspacing="0px";
  tb.className="symchartleft";
  
  if (iMain>0) {
      var td = tb.insertRow(-1).insertCell(-1);
      td.align="right";
      td.style.height="10px";
      td.innerHTML="<hr style='color:0xfdfdfd'>";
      td = tb.insertRow(-1).insertCell(-1);
      td.align="right";
      td.style.width="80px";
      td.style.height=35*(iMain-1)+20+"px";
      td.style.verticalAlign ="top";
      td.innerHTML="主要症状";
  }
  
  if ( iOther>0) {
      tb.insertRow(-1).insertCell(-1).innerHTML="<hr style='color:0xdddddd'>";
      td = tb.insertRow(-1).insertCell(-1);
      td.align="right";
      td.innerHTML="次要症状";
  }
  
  flashDiv.parentNode.insertBefore(tb,flashDiv);

}
function formatSymptomFlashData(startDate,endDate, bForce)//id=0,生成所有的，
{
    g_vSymptomStrs=[];
    var xResult = g_vSymptomXmlDoc.getElementsByTagName("result")[0];
    
    var xSymptomHistories =xResult.getElementsByTagName("symptomhistories")[0].getElementsByTagName("symptomhistory");
    if(xSymptomHistories.length==0)
    {
        var iUin=GetUin();
        var iParamUin=getURLParam("uin",g_sSymptomUrl);
        if( _$(getSymptomFlash()+"1") == null ) return false ;
        
        if (iParamUin>0 && iUin!= iParamUin) _$(getSymptomFlash()+"1").parentNode.innerHTML="<div class='NO_RECORD_CHART'>该用户尚未添加相关信息</div>";
        else _$(getSymptomFlash()+"1").parentNode.innerHTML="<div class='NO_RECORD_CHART'>请您<a class='NO_RECORD_CHART_A' href='/Pages/Alpha/SymptomHistory/Index.aspx'>添加</a>相关信息</div>";
        return false;
    }
    printData(1,10, xSymptomHistories.length);
    var bgcolor='"bg_colour": "#FFFFFF"';
    var now = parseDate(xResult.getAttribute("now"));
    g_vNow=now;
    var confirmDate = parseDate(xResult.getAttribute("confirmdate"));
    if (typeof(endDate)=="undefined") endDate = now ;
    if(typeof(startDate)=="undefined") {startDate = parseDate(xResult.getAttribute("diseasestart"));bForce=false;}
    var startValue = 0 ;
    //format Symptom history        
    var vSymptomNames=["symptomid", "recorddate","degree","type","surveyid","symptomname"];
    var vSymptomHistories=[];
    var vSymptoms={};
    var curDate ;
    var sortedMainSymptoms=[];
    var sortedOtherSymptoms=[];
    for(var i=0;i<xSymptomHistories.length;++i) 
    {
        //var checkid=xLabChecks[i].getAttribute("symptomid");        
        vSymptomHistories.push(xml2array(xSymptomHistories[i],vSymptomNames));
        var symptomid=vSymptomHistories[i]["symptomid"];
        var vSymptomGroup = vSymptoms[symptomid] ;
        if ( typeof(vSymptomGroup) == "undefined") 
        {
            vSymptomGroup = [i];
            vSymptoms[symptomid] = vSymptomGroup ;
            if (vSymptomHistories[i]["type"]=="0") sortedMainSymptoms.push(symptomid);
            else sortedOtherSymptoms.push(symptomid);
        }
        else
        {
            vSymptomGroup.push(i) ;
        }
        
        curDate = parseDate(vSymptomHistories[i]["recorddate"]);
        if (typeof(bForce)=="undefined" || !bForce) 
        {
            if ( curDate<startDate ) startDate = curDate ;
        }
    }
    //format the xaxis labels
    var xLabels = [];
    var iCur=4;
    var ElementValues={};
    var vXDistance = Math.ceil(distanceDate(startDate,endDate)/(iCur-1.0));//alert("distance:"+distanceDate(startDate,endDate)+"unit:"+vXDistance);
    --iCur;
    curDate = endDate;
    do 
    {
        xLabels[iCur] = curDate.toCommonString();
        startDate = curDate ;	
        curDate = getNextDay(curDate, -vXDistance);
    } while(--iCur >=0 );
   
    var xUnit = (distanceDate(startDate, endDate)+0.0)/(xLabels.length-1) ;
    iCur=0;
    {  
        //var labChecks = vCharts[chartindex];
        var sTitle='"title":{"text":"'+'","style": "{font-size: 20px;color:#0000ff;font-family:Verdana;text-align:center}"}';
        //format yAxis
        var YAxisLabels=[];
        //对于yaxis
        for(var iSymptomId in vSymptoms)
        {
            ElementValues[iSymptomId]=[];
        }
        //format Element for each chart
        var vSymptom ;
        var date,nextDate;
        var left,right ;
       iCur=0;
        //format other symptom
        for(var j=0; j< sortedOtherSymptoms.length ;++j)
        {
            var iSymptomId = sortedOtherSymptoms[j];
            YAxisLabels[iCur++] = vSymptomHistories[vSymptoms[iSymptomId][0]]["symptomname"];
            var aSymptoms=vSymptoms[iSymptomId];
            for(var k=0; k<aSymptoms.length; ++k)
            {
                var vSymptom=vSymptomHistories[aSymptoms[k]];
                date=parseDate(vSymptom["recorddate"]);
                if(date < startDate) continue ;
                if ( date > endDate) break;
                if (k==aSymptoms.length-1) nextDate = now ;
                else nextDate = parseDate(vSymptomHistories[aSymptoms[k+1]]["recorddate"]) 
                if (nextDate > endDate) nextDate = endDate ;
                left = (distanceDate(startDate,date)/xUnit).toFixed(3) ;
                right = (distanceDate(startDate,nextDate)/xUnit).toFixed(3) ;
                ElementValues[iSymptomId].push('"left":'+left+',"right":'+right+',"colour":"'+GetSymptomDegreeColor(parseInt(vSymptom["degree"]))+'","tip":"'+vSymptom["symptomname"]+":"+GetSymptomDegreeText(vSymptom["degree"])+"<br>"+date.toCommonString()+'--'+nextDate.toCommonString()+'"');   
            }
        }
        //format main symptom
        for(var j=0; j< sortedMainSymptoms.length ;++j)
        {
            var iSymptomId = sortedMainSymptoms[j];
            YAxisLabels[iCur++] = vSymptomHistories[vSymptoms[iSymptomId][0]]["symptomname"];
            var aSymptoms=vSymptoms[iSymptomId];
            for(var k=0; k<aSymptoms.length; ++k)
            {
                var vSymptom=vSymptomHistories[aSymptoms[k]];
                date=parseDate(vSymptom["recorddate"]);
                if(date < startDate) continue ;
                if ( date > endDate) break;
                if (k==aSymptoms.length-1) nextDate = now ;
                else nextDate = parseDate(vSymptomHistories[aSymptoms[k+1]]["recorddate"]); 
                if (nextDate > endDate) nextDate = endDate ;
                left = (distanceDate(startDate,date)/xUnit).toFixed(3) ;
                right = (distanceDate(startDate,nextDate)/xUnit).toFixed(3) ;
                ElementValues[iSymptomId].push('"left":'+left+',"right":'+right+',"colour":"'+GetSymptomDegreeColor(parseInt(vSymptom["degree"]))+'","tip":"'+vSymptom["symptomname"]+":"+GetSymptomDegreeText(vSymptom["degree"])+"<br>"+date.toCommonString()+'--'+nextDate.toCommonString()+'"');   
            }
        }
        var YAxisLabelsLeft =[];
        for(var i=0;i < YAxisLabels.length ; ++i)YAxisLabelsLeft.push(" ");  
        var sRightYAxis ='"y_axis_right":{"max":'+(YAxisLabels.length-1)+',"step":1, "labels":["'+YAxisLabels.join('","')+'"] },"y2_label_style":"12,#000000","y_label_style":"12,#000000"';
        var sYAxis ='"y_axis":{"offset":20,"max":'+(YAxisLabels.length-1)+',"step":1,"size":25,"colour": "#dddddd", "labels":["'+YAxisLabelsLeft.join('","')+'"] }';
        var sElementValues=[];
        var iCurSymptom=0;
        //format main symptom  
        for(var i=sortedMainSymptoms.length-1;i>=0;--i)
        {
            var iSymptom = sortedMainSymptoms[i];
            sElementValues.push('"type": "hbar", "index":'+sElementValues.length+',"style": "{color: #736AFF;}","values":[{'+ElementValues[iSymptom].join("},{")+'}]');
        }
        //format other symptom
        for(var i=sortedMainSymptoms.length+sortedOtherSymptoms.length-1;i>=sortedMainSymptoms.length;--i)
        {
            var iSymptom = sortedOtherSymptoms[i-sortedMainSymptoms.length];
            sElementValues.push('"type": "hbar", "index":'+sElementValues.length+',"style": "{color: #736AFF;}","values":[{'+ElementValues[iSymptom].join("},{")+'}]');
        }
        var iShapeHeight=sortedOtherSymptoms.length+0.5-1;
        if (sortedOtherSymptoms.length>0 && sortedMainSymptoms.length>0) 
        {
            var sMainOtherShape= '"type": "shape", "colour": "#80B11A", "values": [ { "x": '+0+', "y": '+(iShapeHeight-0.1)+' }, { "x":'+xLabels.length+', "y": '+(iShapeHeight-0.1)+' }, { "x": '+xLabels.length+', "y": '+(iShapeHeight+0.1)+' }, { "x": '+0+', "y": '+(iShapeHeight+0.1)+' } ] ';
            //sElementValues.push(sMainOtherShape);
        }
        _$(getSymptomFlash()+"1").height=35*sElementValues.length+20+20;
        CreateMainOtherSymptom(1,sortedMainSymptoms.length, sortedOtherSymptoms.length);
        var sXAxis ='"x_axis":{"offset":"10px", "max":'+(xLabels.length-1)+',"labels":{"rotate":0.1,"labels":["'+xLabels.join('","')+'"]}}';
        var sElements='"elements":[{'+sElementValues.join('},{')+'}]';
        var sHoverTip='"tooltip": { "mouse": 2, "stroke": 1, "colour": "#000000", "background": "#ffffff" }'
        g_vSymptomStrs.push('{'+sTitle+','+sXAxis+','+sYAxis+','+sRightYAxis+','+sElements+','+bgcolor+','+sHoverTip+'}');
    }
    return true ;
}
function showSymptomFlash(id)
{
    var tmp = _$(getSymptomFlash()+id); 
    try{tmp.load(g_vSymptomStrs[id-1]);}
    catch(e){}
}
function loadSymptomFlashData(id)
{	
	function OnSucc(xmlDoc)
    { 
        g_vSymptomXmlDoc = xmlDoc ;
        if (!formatSymptomFlashData()) return ;
        showSymptomFlash(id);
        if (typeof(g_chartwidth)=="undefined") g_chartwidth=720;
        for(var iCur=2; iCur<=g_vSymptomStrs.length;++iCur)swfobject.embedSWF("/support/swfchart/open-flash-chart.swf", getSymptomFlash()+(iCur), g_chartwidth+'', "350","9.0.0", "expressInstall.swf",{'id':''+iCur});
    }
    
    function OnFail(xmlDoc)
    {
        alert("获取数据失败");
    }
    if (id == 1)
    {   
         CreateFlashDegreeText(id);
        if (typeof(g_sSymptomUrl)=="undefined") g_sSymptomUrl = "/Pages/Alpha/SymptomHistory/SymptomHistory.aspx";
        getResultXml(g_sSymptomUrl,OnSucc,OnFail,OnFail);
    }
    else if (id <= g_vSymptomStrs.length) 
    {
          var tmp = _$("Symptomchart"+id); 
          showSymptomFlash(id);
    }
}
function showSymptomFlashMode(i,dStart,dEnd)
{
    var enddate = g_vNow;
    var startdate;
    switch(i)
    {
        case 1:startdate = getPreBeginMonthDate(enddate,3);break;
        case 2:startdate = getPreBeginMonthDate(enddate,6);break;
        case 3:startdate = getPreBeginMonthDate(enddate,12);break;
        case 4:startdate = getPreBeginMonthDate(enddate,36);break;
        case 5:
            startdate = dStart < dEnd ?　dStart : dEnd ;
            enddate = dStart  > dEnd ?　dStart : dEnd ;
            if (startdate==enddate) 
            {
                alert("起始日期和终止日期相同");
                return ;
            }
        default:break;
    } 
    if(!formatSymptomFlashData(startdate,enddate, true)) return ;
    showSymptomFlash(1);
}

function printData(iPageNo, iPageNum, iTotal)
{
    var oParent = _$("symptom_list");
    if (oParent==null) return ;
    var xResult=g_vSymptomXmlDoc.getElementsByTagName("result")[0];
	var sHtml = document.body.innerHTML.between("<!--TP.LIST","TP.LIST-->");
	var degreeNames={0:"无",1:"轻度",2:"中度",3:"重度"};
	var degreeImgs = {0:"none.png", 1:"mild.png", 2:"moderate.png", 3:"severe.png"};
	var mapName=[
			['id','<%id%>'],
			['degree','<%imgsrc%>', function(v){ return "/support/alpha/symptom/"+degreeImgs[v]}],
			['degree','<%degreeName%>', function(v){ return degreeNames[v].escHtml()}],
			['recorddate','<%date%>',function(v){ return parseDate(v).toCommonString()}]
			];
	var iStart = (iPageNo-1)*iPageNum ;
	var iEnd   = iStart + iPageNum ;
	iEnd = iEnd > iTotal ? iTotal : iEnd;
	
	showXmlNode(xResult, oParent, "symptomhistory",sHtml, mapName, iStart, iEnd);
   
    iTotalPageNum = Math.ceil(iTotal/iPageNum);      
    showPage(iPageNo,iTotalPageNum,function(n){return "javascript:printData("+n+","+iPageNum+","+iTotal+");";},document.getElementById("ID_page"),0);
}